//
//  PictureSelectorController.swift
//  微博项目
//
//  Created by zhaoyinpeng on 16/3/17.
//  Copyright © 2016年 zhaoyinpeng. All rights reserved.
//

import UIKit
import SnapKit
private let reuseIdentifier = "Cell"

//图片之间的间距
private let pictureCleeMargin: CGFloat = 1
private let coloumImageCount: CGFloat = 4

//.最多上传的图片
private let maxImageCount = 3
class PictureSelectorController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init() {
        //.必须使用super调用指定构造函数
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumInteritemSpacing = pictureCleeMargin
        layout.minimumLineSpacing = pictureCleeMargin
        //.设置四周边距
        layout.sectionInset = UIEdgeInsets(top: pictureCleeMargin, left: pictureCleeMargin, bottom: 0, right: pictureCleeMargin)
        
        let w = (ScreenWidth - (coloumImageCount + 1) * pictureCleeMargin) / coloumImageCount
        layout.itemSize = CGSize(width: w, height: w)
        super.init(collectionViewLayout: layout)
        
        //.设置颜色
        self.collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //.注册
        self.collectionView?.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    
}

extension PictureSelectorController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let detla = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        
        //.没创建一个cell 就让控制器遵守 cell的协议
        cell.selectorDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        
        if indexPath.item == imageList.count {
            cell.image = nil
        }else {
            
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}

//.遵守协议
extension PictureSelectorController: PictureSelectorCellDelegate{
    func userWillChosePicture() {
        //.实例化一个 pick
        let picker = UIImagePickerController()
        
        //.指定选择器的代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        //.根据cell 获取点击的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            //.获取对应的item 删除数组中对应角标下得元素
            imageList.removeAtIndex(indexPath.item)
            
            
            //.刷新页面
            collectionView?.reloadData()
        }
    }
}

extension PictureSelectorController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    //.实现协议方法 实现了这个协议方法之后  图片选择器的消失 就需要手动设置
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //.将图片保存起来
        imageList.append(image)
        //.刷新界面
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


//.声明协议
protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //.添加图片
    func userWillChosePicture()
    //.删除图片
    func userWillDeletePicture(cell: PictureSelectorCell)
}

//自定义cell

class PictureSelectorCell: UICollectionViewCell {
    
    weak var selectorDelegate: PictureSelectorCellDelegate?
    
    var image: UIImage? {
        didSet{
            //.如果图片为 nil  就隐藏删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    //.添加图片的按钮点击事件
    
    @objc private func addBtnDidClick() {
        if image == nil {
            selectorDelegate?.userWillChosePicture()
        }
        
        
    }
    //.删除按钮 的点击事件
    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWillDeletePicture(self)
    }
    
    //.重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //MARK: 设置UI界面
    private func setupUI() {
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //.添加子控件约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        //.添加按钮点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
        //.设置显示模式
        addBtn.imageView?.contentMode = .ScaleAspectFill
    }
    
    
    //懒加载子视图
    private lazy var addBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_pic_add")
    private lazy var deleteBtn: UIButton = UIFactory.buttonWithImage(nil, backImageName: "compose_photo_close")
    
}


